# 字符串解码: https://leetcode-cn.com/problems/decode-string/solution/zi-fu-chuan-jie-ma-by-leetcode-soluti

class Solution:
    def decodeString(self, s: str) -> str:
        """
            使用栈解决问题
        """
        stack = []
        i = 0
        while i < len(s):
            # 1. 如果第一个字符是数字，那么就取一整个数字
            if ord("0") <= ord(s[i]) and ord(s[i]) <= ord("9"):
                num = ''
                while ord("0") <= ord(s[i]) and ord(s[i]) <= ord("9"):
                    num += s[i]
                    i += 1
                stack.append(int(num))
            # 2. 如果不是右括号，可能是 [ 或者 字母 直接加进去
            elif s[i] != ']':
                stack.append(s[i])
                i += 1
            # 3. 如果为右括号，计算当前结果
            elif s[i] == ']':
                rst = ''
                # 取字符串
                while stack[-1] != '[':
                    rst = stack.pop() + rst
                # 取数字，并且计算结果字符串
                stack.pop()
                num = stack.pop()

                # 计算结果字符串，添加到结果集,并再次进栈
                rst = rst * num
                stack.append(rst)
                i += 1

        return ''.join(stack)


# 还有一种 递归的方式，就不看了~
